package com.weakteam.orderonline.administratorconsole.bean;

import com.weakteam.orderonline.dataresource.service.CompositeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Nail
 */
public class ImageStore implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(ImageStore.class);
    private static final DateFormat fileDateFormat = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss_");

    @Autowired(required=true)
    Properties mainDataProperties;

    @Autowired
    CompositeService compositeService;


    private String contentPath;
    private String imagePath;
    private String mobileImagePath;

    private File imageFolder;
    private File mobileImageFolder;

    private FilenameFilter imageFilter;

    public ImageStore() {
        imageFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".jpg");
            }
        };
    }

    public void createStore() {
        File content = new File(contentPath);
        if (!content.exists()) content.mkdirs();

        this.imageFolder = new File(content, imagePath);
        if (!this.imageFolder.exists()) this.imageFolder.mkdirs();

        this.mobileImageFolder = new File(content, mobileImagePath);
        if (!this.mobileImageFolder.exists()) this.mobileImageFolder.mkdirs();
    }

    public File getImageFile(String name, boolean forMobile) {
        if (forMobile) {
            return new File(this.mobileImageFolder, name);
        } else {
            return new File(this.imageFolder, name);
        }
    }

    public String saveImageFile(InputStream in, String name) {
        Date today = Calendar.getInstance().getTime();
        String fileName = fileDateFormat.format(today) + name;

        File imageFile = new File(this.imageFolder, fileName);
        File mobileImageFile = new File(this.mobileImageFolder, fileName);

        FileOutputStream imageOut = null;
        FileOutputStream imageMobileOut = null;
        try {
            imageOut = new FileOutputStream(imageFile);
            imageMobileOut = new FileOutputStream(mobileImageFile);
            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                imageOut.write(buf, 0, count);
                imageMobileOut.write(buf, 0, count);
            }
            imageOut.close();
            imageMobileOut.close();
        } catch (FileNotFoundException ex) {
            log.debug("saveImageFile file not found exception {}", ex);
        } catch (IOException ex) {
            log.debug("saveImageFile write file exception {}", ex);
        }
        return fileName;
    }

    public void deleteUnnecessaryFiles() {
        Set<String> livePictures = compositeService.getAllPictureFilesList();
        File[] files = this.imageFolder.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            if (!livePictures.contains(fileName)) {
                if (file.delete()) {
                    log.info("file was deleted {}", fileName);
                    System.out.println("file was deleted " + fileName);
                }
            }
        }
        files = this.mobileImageFolder.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            if (!livePictures.contains(fileName) && file.exists()) {
                if (file.delete()) {
                    log.info("file was deleted {}", fileName);
                    System.out.println("file was deleted " + fileName);
                }
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.contentPath = this.mainDataProperties.getProperty("contentPath");
        this.imagePath = this.mainDataProperties.getProperty("imagePath");
        this.mobileImagePath = this.mainDataProperties.getProperty("mobileImagePath");
    }
}
